# -*- coding:utf8 -*-
import json
import traceback
import os
import re
import typing
import base64
from scrapy import Request, FormRequest
from ..signup.sign_chrome import SignChrome
from squirrel_core.commons.utils.tools import calc_str_md5, upload_file
from squirrel_core.frame.spider_makaka import MakakaSpider

file_path = os.environ.get("FILE_PATH", "/")


class spoorts_score(MakakaSpider):
    name = "spoorts_score"
    serialNumber = ""

    def get_ext_requests_or_urls(self, data=None):
        if data and isinstance(data, str):
            data = json.loads(data)
        if data and isinstance(data, typing.MutableMapping):
            self.serialNumber = data.get("serialNumber", "")
            race_id = data.get("spider_config", {}).get("race_id", "")
            user_id = data.get("spider_config", {}).get("user_id", "")
            race_no = data.get("spider_config", {}).get("race_no", "")
            user_name = data.get("spider_config", {}).get("user_name", "")
            race_name = data.get("spider_config", {}).get("race_name", "").replace(" ", "")
            home_url = data.get("spider_config", {}).get("url", "")
            card_num = data.get("spider_config", {}).get("card_num", "")
            if not home_url and not card_num and not user_name:
                self.logger.info("url,user_name和card_num必须存在")
                self.upload_procedure({"serialNumber": self.serialNumber, "code": 101, "message": "url,user_name和card_num必须存在"})
                self.close_after_idle = True
                self.force_to_close_spider = True
            else:
                self.upload_procedure({"serialNumber": self.serialNumber, "code": 100, "message": "任务启动成功"})
                num = "".join(re.findall(r"race_id=(\d+)", home_url)).strip()
                if "register.spoorts.cn" in home_url:
                    host = "sapi.spoorts.cn"
                    header = {
                        "X-Spoorts-Client": "spoorts_api_v2",
                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
                        "Accept": "application/json, text/plain, */*",
                        "X-Seed": "8244",
                        "X-Requested-With": "XMLHttpRequest",
                        "X-Sign": "tjx/eoxKf88TKQFoYWmPX3xO+BA="
                    }
                elif "testreg.spoorts.cn" in home_url:
                    host = "openapi.spoorts.cn"
                    header = {
                        "X-Spoorts-Client": "spoorts_api_v2",
                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
                        "Accept": "application/json, text/plain, */*",
                        "X-Seed": "1340",
                        "X-Requested-With": "XMLHttpRequest",
                        "X-Sign": "3efGjcIeoRb44Z3t/qFtD6Z9vG8="
                    }
                if host:
                    url = f"https://{host}/api/v1/enrolls/query_result_score_info.json?race_id={num}&real_name={user_name}&id_card={card_num}"
                    yield Request(url=url, callback=self.parse, dont_filter=True, errback=self.err_parse, headers=header,
                                  meta={"race_id": race_id, "user_id": user_id, "user_name": user_name, "card_num": card_num,
                                        "race_name": race_name, "num": num, "handle_httpstatus_list": [500]})

    def parse(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        user_name = response.meta.get("user_name", "")
        race_name = response.meta.get("race_name", "")
        num = response.meta.get("num", "")
        proxy_url = response.request.meta.get("proxy", "")
        proxy_pre = response.request.meta.get("proxy_pre", "")
        try:
            self.logger.info(f"开始解析{user_name}的基本成绩:{response.url}")
            data = json.loads(response.text).get("data", {}).get("score_info", {})
            if data:
                race_code = data.get("race_number", "")
                score_data = {"race_name": race_name, "itemName": data.get("subject_name", ""), "index": data.get("good_score_rank", ""), "name": data.get("real_name", ""), "raceNo": race_code,
                              "distance": "", "shotScore": data.get("finished_score", ""), "score_status": "",
                              "score": data.get("good_score", ""), "sectionScore": [], "certImg": ""}
                subject_id = data.get("subject_id", "")
                score_id = data.get("id", "")
                group_id = data.get("group_id", "")
                cert_url = f"https://register.spoorts.cn/#/certificateBig?race_id={num}&subject_id={subject_id}&score_id={score_id}&race_number={race_code}&group_id={group_id}"
                try:
                    dir_path = os.path.join(file_path, "picture", self.name_first)
                    if not os.path.exists(dir_path):
                        os.makedirs(dir_path)
                    img_base64 = SignChrome().get_pic2(cert_url, proxy_url, proxy_pre)
                    image_data = base64.b64decode(img_base64.split(",", 1)[1])
                    pic_name = f'{calc_str_md5(f"{race_code}_{race_id}")}.jpg'
                    save_path = os.path.join(dir_path, pic_name)
                    if not os.path.exists(save_path):
                        with open(save_path, "wb") as f:
                            f.write(image_data)
                        upload_path = f"flow/{race_id}/{user_id}/pic/{pic_name}"
                        upload_flag = upload_file(save_path, upload_path)
                        if upload_flag:
                            self.logger.info(f"{save_path}上传成功：{upload_path}")
                        else:
                            self.logger.info(f"{save_path}上传失败：{upload_path}")
                        score_data["certImg"] = upload_path
                    result_dict = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                   "crawlerType": self.name_second, "data": str(score_data)}
                    result = self.result_item_assembler(response)
                    result['result_data'] = result_dict
                    yield result
                except:
                    result_dict = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                   "crawlerType": self.name_second, "data": str(score_data)}
                    result = self.result_item_assembler(response)
                    result['result_data'] = result_dict
            else:
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str({"msg": "未查到成绩"})}
                yield result
        except Exception:
            self.logger.info(f"查找{user_name}的基本成绩时出错{response.url}：{traceback.format_exc()}")

    def err_parse(self, failure):
        self.logger.warning(f"请求失败：{failure.request.url},错误原因:{traceback.format_exc()}")

